# -*- coding: utf-8 -*-
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
# odoo16
# QQ:35350428
# 邮件:35350428@qq.com
# 手机：13584935775
# 作者：'Amos'
# 公司网址： www.xodoo.cn
# Copyright 昆山一百计算机有限公司
# 日期：2023-09-16
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

import os
from jinja2 import Environment, FileSystemLoader
from odoo import api, fields, models, tools, SUPERUSER_ID, _, Command
from odoo.api import call_kw

# TODO(amos): 加载模板
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
folder_path = BASE_DIR + "/static/templates"  # 相对文件路径
templateLoader = FileSystemLoader(searchpath=folder_path)
env = Environment(loader=templateLoader)
# TODO(amos): 去空格
env.trim_blocks = True
env.lstrip_blocks = True
env.cache_size = 5000  # 默认缓存模板数量
#::::定义全局变量
env.globals.update({
    'layout': 'false',  # 模板出现class_bg，默认模板
    'layout_nav_fixed': 'true',  # 固定侧导航
    'layout_header_fixed': 'true',  # 固定导航条
    'layout_header_color': 'bg-white',  # 导航背景
    'layout_sidenav_color': 'bg-white',  # 侧导航背景
    'layout_footer_color': 'bg-white',  # 页脚背景
})

# TODO(amos): 提供更多格式化方法
env.filters['date_format'] = tools.jinja_filters.date_format
env.filters['reverse'] = tools.jinja_filters.reverse_filter
env.filters['section_filter'] = tools.jinja_filters.section_filter
env.filters['date_filter'] = tools.jinja_filters.date_filter
env.filters['decode'] = tools.jinja_filters.decode
env.filters['split'] = tools.jinja_filters.split
env.filters['list_split'] = tools.jinja_filters.list_split

import logging

_logger = logging.getLogger(__name__)

import odoo
from odoo import http
from odoo.http import request
import json


class workflow(http.Controller):

    @http.route(['/workflow'], type='http', auth="none", website=True, sitemap=True, cors="*", csrf=False)
    def workflow(self, lang="zh_CN", **kw):
        """
        创建工作流
        :param kw:
        :return:
        """
        # TODO(amos): 检查session是否过期
        if not request.session.uid:
            return request.redirect('/web/login')
        # TODO(amos): URL重定向
        if kw.get('redirect'):
            return request.redirect(kw.get('redirect'), 303)
        cr, uid, context, pool = request.cr, request.session.uid, request.context, request.env

        # TODO(amos): 参数化准备
        values = {'user': pool.user}
        values['session_id'] = request.session.sid
        values['csrf_token'] = request.csrf_token()

        ttype = kw.get("ttype", "read")

        workflow_id = kw.get("workflow_id")

        values['mode'] = kw.get("mode", "readonly")  # TODO(amos): readonly,edit,create
        values['model'] = kw.get("model", "")  # TODO(amos): 那一个对象

        model = pool['ir.model'].sudo().search([('model', '=', values['model'])], order="id desc", limit=1) # id = 371
        fields = pool['ir.model.fields'].sudo().search([('model_id', '=', model.id), ('name', '=', 'state')],order="id desc",limit=1) # model.id = 371
        stlection_ids = fields.selection_ids

        values['stlection_ids'] = stlection_ids
        print(stlection_ids)

        # TODO(amos):创建工作流
        lines = []
        for line in stlection_ids:
            pram = {
                'name': line.name,
                'value': line.value,
            }
            lines.append((0, 0, pram))

        values['order_line'] = lines
        values1 = {
            'name': model.name,
            'node_ids': lines,
        }

        param = None
        if ttype == "read":
            param = pool['workflow'].sudo().search([("id", "=", workflow_id)])
        if ttype == "create":
            param = pool['workflow'].sudo().create(values1)

        if param:
            values["workflow_id"] = param.id
            values["str_workflow"] = param.str_workflow
            values["data"] = []
            for i in param.node_ids:
                values["data"].append({
                    "node_id": i.id,
                    "node_number": i.number,
                    "node_name": i.name,
                    "shape": "custom-image"
                })

        template = env.get_template('zh_CN/index.html')
        html = template.render(object=values)
        return html


    @http.route(['/workflow/new'], type='http', auth="none", website=True, sitemap=True, cors="*", csrf=False)
    def workflow_new(self, lang="zh_CN", **kw):
        """
        新建节点
        """
        cr, uid, context, pool = request.cr, request.session.uid, request.context, request.env
        # 获取节点
        params = json.loads(request.httprequest.data)
        ttype = params.get("ttype") # 4
        workflow_id = params.get("workflow_id") # 6
        node_id = params.get("node_id")
        number = params.get("number")
        name = params.get("name", "")

        str_workflow = params.get("str_workflow", "")

        workflow_datas = params.get("workflow_list", {})
        edge = workflow_datas.get("edge") if workflow_datas else []
        node = workflow_datas.get("node") if workflow_datas else []

        # 整体work_flow
        pool["workflow"].sudo().search([("id", "=", workflow_id)]).write({"str_workflow": str_workflow})

        data = {}
        errmsg = True
        if ttype == 1:  # 创建node
            node_params = {
                "workflow_id": workflow_id,
                "name": name,
                "value": name,
                "number": number
            }
            workflow_node = pool["workflow.node"].sudo().create(node_params)
            data = {"node_id": workflow_node.id}

        if ttype == 2:  # 修改
            info = {}
            if name:
                info.update({"name": name, "value": name})
            workflow_node = pool["workflow.node"].sudo().search([()]).write(info)
            data = {"node_id": workflow_node.id}
        if ttype == 3:  # 删除
            res = pool["workflow.node"].sudo().browse(node_id).unlink()
            data = {"res": res}
        if ttype == 4:  # 创建line,修改node
            try:
                if edge: # 线
                    for v in edge:
                        line_params = {
                            "number": v["node_number"],
                            "start_id": v["source"]["node_id"],
                            "end_id": v["target"]["node_id"],
                            "workflow_id": workflow_id
                        }
                        pool["workflow.line"].sudo().create(line_params)
                if node: # 点
                    for i in node:
                        edge_params = {
                            "x": i["position"]["x"],
                            "y": i["position"]["y"]
                        }
                        if i.get("size"):
                            edge_params.update({
                                "width": i["size"]["width"],
                                "height": i["size"]["height"],
                            })
                        pool["workflow.node"].sudo().search([("number", "=", i["node_number"])]).write(edge_params)
            except Exception as r:
                errmsg = False
                _logger.error(r)

        value = {
            "code": 1 if errmsg else 0,
            "errmsg": errmsg,
            "message": "作操成功",
            "data": data
        }
        return json.dumps(value)

    @http.route(['/workflow/preview'], type='http', auth="public", website=True, sitemap=True)
    def workflow_preview(self, lang="zh_CN", **kw):
        """
        预览工作流接口
        """
        # TODO(amos): 检查session是否过期
        if not request.session.uid:
            return request.redirect('/web/login')

        # TODO(amos): URL重定向
        if kw.get('redirect'):
            return request.redirect(kw.get('redirect'), 303)
        cr, uid, context, pool = request.cr, request.session.uid, request.context, request.env

        # TODO(amos): 参数化准备
        values = {'user': pool.user}
        values['session_id'] = request.session.sid
        values['csrf_token'] = request.csrf_token()

        values['mode'] = kw.get("mode", "readonly")  # TODO(amos): readonly,edit,create

        template = env.get_template('zh_CN/preview.html')
        html = template.render(object=values)
        return html

    @http.route(['/workflow/state'], type='http', auth="public", website=True, sitemap=True)
    def workflow_state(self, lang="zh_CN", **kw):
        """
        当前工作流状态
        """
        # TODO(amos): 检查session是否过期
        return ''

    @http.route(['/workflow/approval'], type='http', auth="public", website=True, sitemap=True)
    def workflow_approval(self, lang="zh_CN", **kw):
        """
        当前工作流状态
        """
        # TODO(amos): 检查session是否过期
        return ''

    @http.route(['/workflow/<string:method>'], type='http', auth="public", website=True, sitemap=True, cors="*", csrf=False)
    def workflow_restructure(self, model, **kw):
        """
        编辑工作流节点
        """
        cr, uid, context, pool = request.cr, request.session.uid, request.context, request.env
        params = json.loads(request.httprequest.data)
        method = kw.get("method")
        node_id = kw.get("node_id")
        workflow_id = kw.get("workflow_id")
        data = {}
        if method == "read_all":
            res = pool[model].sudo().search_read([("id", "=", node_id)])
            if not res:
                data["code"] = -1
                data["message"] = "res not found"
                return json.dumps(data)
            res[0].pop("__last_update")
            data["data"] = res
            groups_ids = res[0].get("groups_ids")
            users_ids = res[0].get("users_ids")
            res_groups = pool["res.groups"].sudo().search_read([("id", "in", groups_ids)], ["name"])
            res_users = pool["res.users"].sudo().search_read([("id", "in", users_ids)], ["name"])
            workflow_id = res[0].get("workflow_id")[0]
            v = pool["workflow"].sudo().search([("id", "=", workflow_id)])
            data["company_id"] = v.company_id if v.company_id else False
            data["groups_ids"] = res_groups
            data["users_ids"] = res_users
        if method == "selection":
            res = pool[model].sudo().name_search(name="", limit=10)
            res_list = []
            if res:
                for k, v in res:
                    res_list.append({"id": k, "text": v})
            data["result"] = res_list
        if method == "selection_node":
            res = pool[model].sudo().search_read([("workflow_id", "=", int(workflow_id))], ["name"])
            data["result"] = res
        if method == "save":
            user_ids = params.get("user_ids")
            groups_ids = params.get("groups_ids")
            types = params.get("type")
            info = pool[model].sudo().browse(int(node_id))
            if user_ids:
                info.users_ids = [(6, 0, user_ids)]
                info.type = "固定审核人"
            if groups_ids:
                info.groups_ids = [(6, 0, groups_ids)]
                info.type = "权限组"
            if types and not user_ids and not groups_ids:
                info.type = types
            value = params.get("value")
            if value:
                info.write(value)
            data["message"] = info.id
        data["code"] = 1
        return json.dumps(data)
